<?php
namespace control;
/*
*客户类
*/

use JetBrains\PhpStorm\NoReturn;

class clientClass extends adIndexClass
{
    private const title = '客户';
    private const page = 'client';
    private const table = 'kehu';
    private const tableAddr = 'sales_contract_address'; # 地址表

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'logSearch':
                $tr = [
                    'time'          => [
                        'name'  => L('client.logSearch.operateTime'),
                        'width' => 400,
                        'sort' => 1,
                    ],
                    'staffName' => [
                        'name'  => L('client.logSearch.operator'),
                        'width' => 400,
                    ],
                    'type'  => [
                        'name'  => L('client.logSearch.operateType'),
                        'width' => 400,
                        'sort' => 1,
                    ],
                    'text'         => [
                        'name'  => L('client.logSearch.remark'),
                        'width' => 400,
                    ]
                ];
                break;
            case 'visitSearch':
                $tr = [
                    'member'          => [
                        'name'  => L('client.visitSearch.visitor'),
                        'width' => 300,
                    ],
                    'theme' => [
                        'name'  => L('client.visitSearch.theme'),
                        'width' => 300,
                    ],
                    'factStartTime'  => [
                        'name'  => L('client.visitSearch.time'),
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'hour'         => [
                        'name'  => L('client.visitSearch.hour'),
                        'width' => 300,
                    ],
                    'achievement'          => [
                        'name'  => L('client.visitSearch.achievement'),
                        'width' => 300,
                    ]
                ];
                break;
            case 'cooperationSearch':
            case 'allClueSearch':
                $tr = [
                    'companyName'          => [
                        'name'  => "{l.client.homeSearch.companyName}",
                        'width' => 100,
                    ],
                    'tags' => [
                        'name'  => '{l.client.homeSearch.tags}',
                        'width' => 150,
                    ],
                    'nature'  => [
                        'name'  => "{l.client.homeSearch.nature}",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'contactName'         => [
                        'name'  => "{l.client.homeSearch.contactName}",
                        'width' => 100,
                    ],
                    'contactTel'          => [
                        'name'  => "{l.client.homeSearch.contactTel}",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'landline'          => [
                        'name'  => "{l.client.homeSearch.landline}",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => "{l.client.homeSearch.workFlow}",
                        'width' => 100,
                    ],
                    'source'          => [
                        'name'  => "{l.client.homeSearch.source}",
                        'width' => 100,
                    ],
                    'manager'          => [
                        'name'  => '{l.client.homeSearch.manage}',
                        'width' => 100,
                    ],
                    'pool'          => [
                        'name'  => "{l.client.homeSearch.pool}",
                        'width' => 100,
                    ],
                    'time'          => [
                        'name'  => "{l.client.homeSearch.time}",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'followRecord'          => [
                        'name'  => "{l.client.homeSearch.followRecord}",
                        'width' => 150,
                    ],
                    'lastFollowTime'          => [
                        'name'  => "{l.client.homeSearch.followTime}",
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'companyName'          => [
                        'name'  => "{l.client.homeSearch.companyName}",
                        'width' => 150,
                    ],
                    'tags' => [
                        'name'  => '{l.client.homeSearch.tags}',
                        'width' => 150,
                    ],
                    'nature'  => [
                        'name'  => "{l.client.homeSearch.nature}",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'contactName'         => [
                        'name'  => "{l.client.homeSearch.contactName}",
                        'width' => 100,
                    ],
                    'contactTel'          => [
                        'name'  => "{l.client.homeSearch.contactTel}",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'landline'          => [
                        'name'  => "{l.client.homeSearch.landline}",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => "{l.client.homeSearch.workFlow}",
                        'width' => 100,
                    ],
                    'source'          => [
                        'name'  => "{l.client.homeSearch.source}",
                        'width' => 100,
                    ],
                    'pool'          => [
                        'name'  => "{l.client.homeSearch.pool}",
                        'width' => 100,
                    ],
                    'time'          => [
                        'name'  => "{l.client.homeSearch.time}",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'followRecord'          => [
                        'name'  => "{l.client.homeSearch.followRecord}",
                        'width' => 150,
                    ],
                    'lastFollowTime'          => [
                        'name'  => "{l.client.homeSearch.followTime}",
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        $array = [
            [
                [
                    L('client.homeForm.companyName') => text(array("name" => "companyName")),
                    L('client.homeForm.label')   => text(array("name" => "label")),
                    L('client.homeForm.contactName') => text(array("name" => "contactName")),
                ],
                [
                    L('client.homeForm.contactTel') => text(array("name" => "contactTel")),
                    L('client.homeForm.landline') => text(array("name" => "landline")),
                    L('client.homeForm.workFlow') => select(array("name" => "workFlow", "option" => explode("，", para("clientWorkFlow")))),
                ],
                [
                    L('client.homeForm.source') => select(array("name" => "source", "option" => explode("，", para("clientSource")))),
                    L('client.homeForm.pool')  => selectMultiple(array('table' => 'pool', 'sqlField' => 'name','where'=>"type = '公客池' and coid='".self::$coid."' order by list asc", 'sqlId' => 'id', 'name' => 'poolId', 'class' => 'width200')),
                    L('client.homeForm.time') => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ];
        if ($workFlow == '我协作的') {
            $array[0][] = [
                L('client.homeForm.manager') => selectMultiple(array('table' => 'staff', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager', 'class' => 'width200'))
            ];
        } elseif ($workFlow == '全部客户') {
            $array[0][] = [
                L('client.homeForm.manager') => selectMultiple(array('table' => 'staff', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager', 'class' => 'width200'))
            ];
        }
        return $this->tableShow($array);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('我的客户');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('client.homeSearch.newClient') . "','" . $url . "&fun=edit')\" class='spanButton'>".L('client.homeSearch.new')."</span>\n
<span onclick=\"layer('" . self::page . "','batchAddTags',{})\" class='spanButton'>".L('client.homeSearch.batchAddTags')."</span>\n
                       
                        <span onclick=\"layer('" . self::page . "','transfer',{})\" class='spanButton'>".L('client.homeSearch.transfer')."</span>\n
                        ";
            // <span onclick=\"\" class='spanButton'>发送短信</span>\n
            // <span onclick=\"layer('" . self::page . "','publicClient',{})\" class='spanButton'>".L('client.homeSearch.publicClient')."</span>\n
            // <span onclick=\"layer('" . self::page . "','pool',{})\" class='spanButton'>".L('client.homeSearch.poolChange')."</span>\n

        }
        //导入
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('client.homeSearch.del')."</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "tags" => $this->post('label'),//标签
            "companyName" => $this->post('companyName'),//客户名称
            "contactName" => $this->post('contactName'),//客户名称
            "contactTel" => $this->post('contactTel'),//联系手机
            "landline" => $this->post('landline'),//电话
        );
        //全等查询数组
        $equal = array(
            'coid'=>self::$coid,
            "manager" => self::$stid,
            "workFlow" => $this->post('workFlow'),//跟进情况
            "source" => $this->post('source'),//客户来源
            "poolId" => $this->post('poolId'),
        );
        //公私客
        $and = " and manager !=''";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => "kehu", "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['khid']),
                "detail" => array("title" => L('client.homeSearch.detail'), "click" => "newIframe('".L('client.homeSearch.detail')."','" . root . "control/adIndex.html?cla=client&fun=detail&id=" . $array['khid'] . "')"),
                "edit" => array("title" => L('client.homeSearch.edit'), "click" => "newIframe('" . L('client.homeSearch.detail') . "','" . $url . "&fun=edit&id=" . $array['khid'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "tags":
                        $tags = '';
                        $kehu_label = find(array('table' => 'kehu_label', 'where'=>"targetId = '$array[khid]' order by list asc"));
                        foreach ($kehu_label['array'] as $val) {
                            $tag_detail = query('tag_detail', "id = '$val[tag_detail_id]'");
                            $tags .= "<span class='background-color-gray' style='margin-right: 5px'>{$tag_detail['name']}</span>";
                        }
                        $row[] = $tags;
                        break;
                    case "pool":
                        $pool = query('pool',"id = '$array[poolId]'");
                        $row[] = $pool['name'];
                        break;
                    case "followRecord":
                        //最后的一条跟进记录
                        $follow = query("follow", " target = '客户' and targetId = '$array[khid]' order by time desc ");
                        $row[] = $follow['text'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 转为公客
     */
    public function publicClient(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('client.publicClient.tips')."：" =>L('client.publicClient.TipsWrod'),
            ),
        )
        ));
        //返回
        return $this->layer(array("title" => L('client.publicClient.publicClient'), 'winFix' => true,'width'=>600, "height" => 200, "html" => $html, 'formTwo' => 'listForm,allClueForm'));
    }

    /**
     *  转为公客编辑
     */
    public function publicClientEdit(): bool|string
    {
        $listId = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        if (!$this->power(self::page, 'edit') && !$this->power('allClient','admin')) {
            $json['warn'] = L('client.publicClientEdit.power');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('client.publicClientEdit.empty');
        }  else {
            $x = 0;
            foreach ($listId as $id) {
                //线索
                $info = query(self::table, " khid = '$id'");
                if ($info['manager'] == self::$stid || $this->power(self::page,'admin') || $this->power('allClient','admin')) {
                    $warn = update(array(
                        'table' => self::table,
                        'field' => [
                            'manager' => '',
                            'collaborator'=>'',
                            'see'=>'',
                        ],
                        'where' => "khid = '$id'"
                    ));
                    if (in_array($warn, ['新增成功', '更新成功'])) {
                        $x++;
                        $text = str_replace(['{{staffName}}','{{companyName}}','{{id}}'], [$this->control['name'],$info['companyName'],$id], L('client.publicClientEdit.logText'));
                        $this->logText(["type" => self::page, "text" => $text]);
                        //日志
                        $this->logWrite($id, '转为公客', str_replace(['{{staffName}}'], [$this->control['name']], L('client.publicClientEdit.logWrite')));
                    }
                } else {
                    $text = str_replace(['{{staffName}}','{{companyName}}'], [$this->control['name'],$info['companyName']], L('client.publicClientEdit.failLog'));
                    $this->logText(["type" => self::page, "text" => $text]);
                }
            }
            $json['warn'] = 2;
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('client.publicClientEdit.warn'));
        }
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function cooperationOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('我协作的');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 我协作的
     *
     */
    public function cooperation(): bool|string
    {
        $html = $this->cooperationOptions(false);
        $button = "";
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function cooperationSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "tags" => $this->post('label'),//标签
            "companyName" => $this->post('companyName'),//客户名称
            "contactName" => $this->post('contactName'),//客户名称
            "contactTel" => $this->post('contactTel'),//联系手机
            "landline" => $this->post('landline'),//电话
        );
        //全等查询数组
        $equal = array(
            'coid'=>self::$coid,
            "manager" =>$this->post('manager'),
            "workFlow" => $this->post('workFlow'),//跟进情况
            "source" => $this->post('source'),//客户来源
            "poolId" => $this->post('poolId'),
        );
        //公私客
        $and = " and manager !='' and collaborator like '%" . self::$stid . "%'";

        if ($this->post('time')) {
            $timeArr = explode(' ~ ', $this->post('time'));
            $and .= " and date(time) >='{$timeArr[0]}' and date(time) <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => "kehu", "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['khid']),
                "detail" => array("title" => L('client.homeSearch.detail'), "click" => "newIframe('".L('client.homeSearch.detail')."','" . root . "control/adIndex.html?cla=client&fun=detail&id=" . $array['khid'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "tags":
                        $tags = '';
                        $kehu_label = find(array('table' => 'kehu_label', 'where'=> "targetId = '$array[khid]' order by list asc"));
                        foreach ($kehu_label['array'] as $val) {
                            $tag_detail = query('tag_detail', "id = '$val[tag_detail_id]'");
                            $tags .= "<span class='background-color-gray' style='margin-right: 5px'>{$tag_detail['name']}</span>";
                        }
                        $row[] = $tags;
                        break;
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "pool":
                        $pool = query('pool',"id = '$array[poolId]'");
                        $row[] = $pool['name'];
                        break;
                    case "followRecord":
                        //最后的一条跟进记录
                        $follow = query("follow", " target = '客户' and targetId = '$array[khid]' order by time desc ");
                        $row[] = $follow['text'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='cooperationForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function allClueOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('全部客户');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function allClue(): bool|string
    {
        $html = $this->allClueOptions(false);
        //控件
        $button = "";
        if ($this->power('allClient', "admin")) {
            $button .= "
                         <span onclick=\"layer('" . self::page . "','transfer',{})\" class='spanButton'>".L('client.homeSearch.transfer')."</span>\n
                        ";
            //                         <span onclick=\"layer('" . self::page . "','publicClient',{})\" class='spanButton'>".L('client.homeSearch.publicClient')."</span>\n


        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function allClueSearch(): bool|string
    {
        //自己的，协作的，直接下级的
        //like查询数组
        $like = array(
            "tags" => $this->post('label'),//标签
            "companyName" => $this->post('companyName'),//客户名称
            "contactName" => $this->post('contactName'),//客户名称
            "contactTel" => $this->post('contactTel'),//联系手机
            "landline" => $this->post('landline'),//电话
        );
        //全等查询数组
        $equal = array(
            'coid'=>self::$coid,
            "manager" =>$this->post('manager'),
            "workFlow" => $this->post('workFlow'),//跟进情况
            "source" => $this->post('source'),//客户来源
            "poolId" => $this->post('poolId'),
        );
        //公私客
        $and = " and manager !=''";

        if ($this->power('allClient', "seeAll")) {
            //查看所有客户的权限
            $and .= " and 1=1";
        }elseif($this->power('allClient', "seeGroup")){
            //查看本组（直接下级）
            $and .= " and (collaborator like '%" . self::$stid . "%'  or manager = '" . self::$stid . "' or manager in (select stid from staff where manager = '" . self::$stid . "'))";
        }else{
            //查看自己
            $and .= " and (collaborator like '%" . self::$stid . "%'  or manager = '" . self::$stid . "')";
        }

        if ($this->post('time')) {
            $timeArr = explode(' ~ ', $this->post('time'));
            $and .= " and date(time) >='{$timeArr[0]}' and date(time) <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("allClueForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['khid']),
                "detail" => array("title" => L('client.homeSearch.detail'), "click" => "newIframe('".L('client.homeSearch.detail')."','" . root . "control/adIndex.html?cla=client&fun=detail&id=" . $array['khid'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "tags":
                        $tags = '';
                        $kehu_label = find(array('table' => 'kehu_label','where'=> "targetId = '$array[khid]' order by list asc"));
                        foreach ($kehu_label['array'] as $val) {
                            $tag_detail = query('tag_detail', "id = '$val[tag_detail_id]'");
                            $tags .= "<span class='background-color-gray' style='margin-right: 5px'>{$tag_detail['name']}</span>";
                        }
                        $row[] = $tags;
                        break;
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "pool":
                        $pool = query('pool',"id = '$array[poolId]'");
                        $row[] = $pool['name'];
                        break;
                    case "followRecord":
                        //最后的一条跟进记录
                        $follow = query("follow", " target = '客户' and targetId = '$array[khid]' order by time desc ");
                        $row[] = $follow['text'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='allClueForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " khid = '" . $this->get('id') . "' ");
        $button[]  = [
            "name"  => L('public.save'),
            "type"  => "点击事件",
            "cla"   => $this->get('cla'),
            "fun"   => "subForm('" . self::page . "EditForm', root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
            "post"  => ["id" => $this->get('id')],
            'style' => 'li-btn-blue-bg',
        ];
        $tags = '';
        $kehu_label = find(array('table' => 'kehu_label', 'where'=>"targetId = '$info[khid]' and targetId <> '' order by list asc"));
        foreach ($kehu_label['array'] as $array) {
            $tag_detail = query('tag_detail', "id = '$array[tag_detail_id]'");
            $tags .= "<span class='background-color-gray' style='margin-right: 5px'>{$tag_detail['name']}<input name='labelMxId[]' type='hidden' value='{$tag_detail['id']}'></span>";
        }

        // 收货地址
        /*$saleContractClass = new salesContractClass();
        $addTr[] = ['', '{l.salesContract.editPage.name}', '{l.salesContract.editPage.tel}', '{l.salesContract.editPage.address}'];
        $type = 'address';
        $result = find(array(
            'field' => "id,name,tel,address",
            'table' => self::tableAddr." where orderId = '{$info['khid']}' order by time DESC"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array = $saleContractClass->prefixArrayKeys($array,$type);
                $array['list'] = $k+1;
                $addTr[] = $saleContractClass->addressRow($array);
            }
        }else{
            $addTr[] = $saleContractClass->addressRow([$type.'id'=>self::getId(), 'list'=>1]);
        }*/
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            L('client.edit.contactInfo') => [
                [
                    must . L('client.edit.companyName')."：" => text(["name" => "companyName", 'class' => 'text', "value" => $info['companyName']]),
                    must . L('client.edit.nature')."：" => select(["name" => "nature", 'class' => 'text', 'title' => '请选择', 'option' => explode('，', para('clientNature')), "value" => $info['nature']]),
                    must . L('client.edit.contactName')."：" => text(["name" => "contactName", 'class' => 'text', "value" => $info['contactName']]),
                ],
                [
                    L('client.edit.contactIdentity')."：" => text(["name" => "contactIdentity", 'class' => 'text', "value" => $info['contactIdentity']]),
                    L('client.edit.contactTel')."：" => text(["name" => "contactTel", 'class' => 'text', "value" => $info['contactTel']]),
                    L('client.edit.landline')."：" => text(["name" => "landline", 'class' => 'text', "value" => $info['landline']]),
                ],
                [
                    L('client.edit.contactWx')."：" => text(["name" => "contactWx", 'class' => 'text', "value" => $info['contactWx']]),
                    L('client.edit.contactQQ')."：" => text(["name" => "contactQQ", 'class' => 'text', "value" => $info['contactQQ']]),
                    L('client.edit.birthDay')."：" => text(["name" => "birthDay", 'class' => 'text', 'laydate' => [], "value" => self::null($info['birthDay'], false)]),
                ],
                [
                    L('client.edit.website')."：" => text(["name" => "website", 'class' => 'text', "value" => $info['website']]),
                    L('client.edit.email')."：" => text(["name" => "email", 'class' => 'text', "value" => $info['email']]),
                    L('client.edit.address')."：" => text(["name" => "address", 'title' => L('client.edit.keyword'), 'class' => 'text', "value" => $info['address']]) . (componentClass::addressIco("layer('" . self::page . "','map',{})")) .
                        hidden(array('name' => 'location', 'value' => $info['lng'] ? ($info['lat'] . ',' . $info['lng']) : '')).
                        hidden(array('name' => 'region', 'value' => $info['region']?:'')),
                ],
                [
                    "单次运费：" => text(["name" => "freight", 'class' => 'text', "value" => $info['freight']]),
                ]
            ],
            L('client.edit.manageInfo') => [
                [
                    L('client.edit.level')."：" => select(["name" => "level", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientLevel')), "value" => $info['level']]),
                    L('client.edit.classify')."：" => select(["name" => "classify", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientType')), "value" => $info['classify']]),
                    L('client.edit.industry')."：" => select(["name" => "industry", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientIndustry')), "value" => $info['industry']]),
                    L('client.edit.scale')."：" => select(["name" => "scale", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientScale')), "value" => $info['scale']]),
                ],
                [
                    L('client.edit.source')."：" => select(["name" => "source", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientSource')), "value" => $info['source']]),

                    L('client.edit.workFlow')."：" => select(["name" => "workFlow", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientWorkFlow')), "value" => $info['workFlow']]),
                    L('client.edit.followTime')."：" => text(["name" => "followTime", 'laydate' => ['type' => 'datetime'], 'class' => 'text', "value" => $info['followTime']]),
                    L('client.edit.pool')."：" => selectMultiple(array('name' => 'poolId', 'title' => L('client.edit.choice'), 'where' => "type = '公客池' and coid = '".self::$coid."'", 'table' => 'pool', 'sqlId' => 'id', 'sqlField' => 'name', 'value' => $info['poolId'])),
                ],
                [
                    must . L('client.edit.manager')."：" => selectMultiple(array('table' => 'staff', "title" => L('client.edit.choice'), 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager', 'value' => $info['manager'] ?: self::$stid)),
                    L('client.edit.collaborator')."：" => selectMultiple(array('table' => 'staff', 'where' => " stid !='$info[manager]'", 'multiple' => true, "title" => L('client.edit.choice'), 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'collaborator[]', 'value' => $info['collaborator'])),
                    L('client.edit.tags')."：" => "<span id='tags'>{$tags}</span><span class='spanButton' style='margin:0' onclick=\"layer('" . $this->get('cla') . "','add_label',$('form[name=clientEditForm]').serialize())\">".L('client.edit.addLabel')."</span>",
                ],
                [
                    L('client.edit.remark')."：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']])
                ],
            ],
            L('client.edit.invoice') => [
                array(
                    "发票类型：" => radio(array("name" => "invoiceType",'value'=>['普票','专票'], "checked" => $info['invoiceType']?:'普票')),
                    "默认税率(%)：" => select(array("name" => "taxRate",'option'=>explode('，',para('taxRate')),'title'=>'请选择', "value" => (float)$info['taxRate']*100)),
                    "默认付款方式：" => select(array("name" => "payType",'option'=>explode('，',para('payType')),'title'=>'请选择', "value" => $info['payType'])),
                    "信用额度：" => text(array("name" => "credits",'unit'=>static::$unit, "value" => $info['credits'])),
                ),
                array(
                    "默认结算方式：" => radio(array("name" => "settleType",'value'=>explode('，',para('supplierSettlement')), "checked" => $info['settleType'])),
                    "对账日：" => text(array("name" => "checkDay","value" => $info['checkDay'])),
                    L('client.edit.invoiceCompany')."：" => text(array("name" => "invoiceCompany", "value" => $info['invoiceCompany'])),
                    L('client.edit.companyBank')."：" => text(array("name" => "companyBank", "value" => $info['companyBank'])),
                ),
                array(
                    L('client.edit.companyBankNum')."：" => text(array("name" => "companyBankNum", "value" => $info['companyBankNum'])),
                    L('client.edit.companyAddress')."：" => text(array("name" => "companyAddress", "value" => $info['companyAddress'])),
                    L('client.edit.companyNum')."：" => text(array("name" => "companyNum", "value" => $info['companyNum'])),
                    L('client.edit.postAddress')."：" => text(array("name" => "postAddress", "value" => $info['postAddress'])),
                ),
            ],
        ]);
        /*$body .= $this->editList([
            'title' => L('salesContract.editPage.shippingAddress'),
            'html' => "<div class='purchaseMx'>" .
                $this->listTable(['tr' => $addTr, 'end' => true]) .
                "</div>",
        ]);*/
        //表单
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $this->get('id')]),
        ]);

        $data['html'] .= <<<efo
<style>
 .font-bold{
   font-size: 14px;font-weight: bold
 }
</style>
<script>
//添加一行
function addRow(e,type){
    $.post(root+'control/adIndex.html?cla=salesContract&fun=addRow',{type:type},function (res){
        $(e).closest('tr').after(res.data);
        resetNumber($(e).closest('tbody'))
    },'json');
}
$(function(){
    $("input[name='address']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=component&fun=getAddress',
        callback:function(data){
            $("[name='location']").val(data.location);
            $("[name='region']").val(data.province+'-'+data.city)
        }
    });
})
</script>
efo;

        //返回
        return $this->tab($data);
    }

    /**
     * 返回标签显示
     */
    public function getTags(): bool|string
    {
        $tagMxId = $this->post('tagMxId');
        $json['html'] = '';
        if (!empty($tagMxId) && is_array($tagMxId)) {
            foreach ($tagMxId as $id) {
                $tag_detail = query('tag_detail', "id = '$id'");
                if (!empty($tag_detail['id'])) {
                    $json['html'] .= "<span class='background-color-gray' style='margin-right: 5px'>{$tag_detail['name']}<input name='labelMxId[]' type='hidden' value='$id'></span>";
                }
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 添加标签
     */
    public function add_label(): bool|string
    {
        $labelMxId = $this->post('labelMxId') ?: [];
        $label_group = find(array('table' => 'tag', 'where' => "type=0 order by time asc"));
        $group_li = '';
        foreach ($label_group['array'] as $index => $array) {
            $group_li .= "<li>{$array['name']}</li><li>";
            $detail_ul = <<<eof
<ul class="label-content-sec-ul client-level">
eof;
            $label_detail = find(array('table' => 'tag_detail', 'where' => "orderId = '$array[id]' order by list asc"));
            foreach ($label_detail['array'] as $value) {
                $checked = '';
                if (in_array($value['id'], $labelMxId)) {
                    $checked = 'background-color-blue';
                }
                $detail_ul .= "<li class='background-color-gray {$checked}' data-id='{$value['id']}'>{$value['name']}</li>";
            }
            $tagMxId = $labelMxId[$index] ?? '';
            $group_li .= "{$detail_ul}<input name='tagMxId[]' type='hidden' value='$tagMxId'></ul></li>";
        }

        $resetWord = L('client.addLabel.reset');
        $cancelWord = L('client.addLabel.cancel');
        $sureWord = L('client.addLabel.sure');
        $selectedWord = L('client.addLabel.selected');
        $unitWord = L('client.addLabel.unit');
        $addLabelWord = L('client.addLabel.addLabel');
        $html = <<<efo
<form name="labelForm">
<div class="label-content">
<ul>
     {$group_li}
</ul>
</div>
<div class="label-footer">
     $selectedWord<span id="label-num">0</span>$unitWord<span class="del-row-button" id="reset" style="margin-left: 20px">$resetWord</span>
     <span class="spanButton" onclick="$('#clientAdd_label').hide()" style="float: right">$cancelWord</span>
     <span class="spanButton li-btn-blue-bg" onclick="confirm_label()" style="float: right">$sureWord</span>
</div>
</form>
<style>
.label-content{
   margin: 10px 20px;height: 570px;border-bottom: 2px dashed rgb(215, 215, 215);
}
.label-content-sec-ul li {
  float: left;margin: 10px 5px;text-align: center;cursor: pointer;
}
.background-color-gray{
  margin-left: 0;
}
.label-content>ul>li{
  display: flex;
}
.label-content>ul>li:nth-child(2n+1){
  padding-left: 5px;
  margin-top: 5px;
}
.label-footer{
  height: 50px;
  line-height: 50px;
  margin: 0 20px;
}
</style>
<script>
//计算标签数量
 function set_label_num(){
    let num =  $(".label-content-sec-ul .background-color-blue").length;
    $("#label-num").html(num);
 }
 //点击标签
 $(".label-content-sec-ul li").on('click',function() {
     let parent = $(this).parent();
     if ($(this).hasClass('background-color-blue')){
          parent.find("li").removeClass('background-color-blue');
          $(this).siblings("input[name='tagMxId[]']").val('');
     }else{
         parent.find("li").removeClass('background-color-blue');
         $(this).addClass('background-color-blue');
         let id = $(this).data('id');
         $(this).siblings("input[name='tagMxId[]']").val(id);
     }
   
     set_label_num();
 })
 //重置标签
 $("#reset").on('click',function (){
     $(".label-content-sec-ul").find("li").removeClass('background-color-blue');
     $(".label-content-sec-ul").find("input[type='hidden']").val('');
     set_label_num();
 })
 //选择标签
function confirm_label(){
    let serialize = $("[name='labelForm']").serialize();
    $('#clientAdd_label').hide();
    $.post(root+'control/adIndex.html?cla=client&fun=getTags', serialize, function (data) {
        $("#tags").empty().append(data.html)
    }, "json");
}
</script>
efo;

        return $this->layer(array("title" => $addLabelWord, "height" => 700, "width" => 900, "zindex" => 3, "html" => $html, "button" => false));
    }


    /**
     * 批量添加标签
     */
    public function batchAddTags(): bool|string
    {
        $label_group = find(array('table' => 'tag', 'where' => "type=0 order by time asc"));
        $group_li = '';
        foreach ($label_group['array'] as $index => $array) {
            $group_li .= "<li>{$array['name']}</li><li>";
            $detail_ul = <<<eof
<ul class="label-content-sec-ul client-level">
eof;
            $label_detail = find(array('table' => 'tag_detail', 'where' => "orderId = '$array[id]' order by list asc"));
            foreach ($label_detail['array'] as $value) {
                $detail_ul .= "<li class='background-color-gray' data-id='{$value['id']}'>{$value['name']}</li>";
            }
            $group_li .= "{$detail_ul}<input name='tagMxId[]' type='hidden' value=''></ul></li>";
        }

        $resetWord = L('client.addLabel.reset');
        $cancelWord = L('client.addLabel.cancel');
        $sureWord = L('client.addLabel.sure');
        $selectedWord = L('client.addLabel.selected');
        $unitWord = L('client.addLabel.unit');
        $addLabelWord = L('client.batchAddTags.batch');
        $html = <<<efo
<form name="labelForm">
<div class="label-content">
<ul>
     {$group_li}
</ul>
</div>
<div class="label-footer">
     $selectedWord<span id="label-num">0</span>$unitWord<span class="del-row-button" id="reset" style="margin-left: 20px">$resetWord</span>
     <span class="spanButton" onclick="$('#clientBatchAddTags').hide()" style="float: right">$cancelWord</span>
     <span class="spanButton li-btn-blue-bg" onclick="confirm_batch()" style="float: right">$sureWord</span>
</div>
</form>
<style>
.label-content{
   margin: 10px 20px;height: 570px;border-bottom: 2px dashed rgb(215, 215, 215);
}
.label-content-sec-ul li {
  float: left;margin: 10px 5px;text-align: center;cursor: pointer;
}
.background-color-gray{
  margin-left: 0;
}
.label-content>ul>li{
  display: flex;
}
.label-content>ul>li:nth-child(2n+1){
  padding-left: 5px;
  margin-top: 5px;
}
.label-footer{
  height: 50px;
  line-height: 50px;
  margin: 0 20px;
}
</style>
<script>
function confirm_batch(){
     let serialize = $("[name='labelForm']").serialize();
     serialize+='&'+$("[name='listForm']").serialize();
     $('#clientAdd_label').hide();
     $.post(root+'control/adIndex.html?cla=client&fun=batchAddTagsEdit', serialize, function (data) {
         if (data.warn == 2) {
            if (data.href) {
              window.location.href = data.href;
            } else {
              window.location.reload();
            }
          } else {
            warn(data.warn);
          }
    }, "json");
}
//计算标签数量
 function set_label_num(){
    let num =  $(".label-content-sec-ul .background-color-blue").length;
    $("#label-num").html(num);
 }
 //点击标签
 $(".label-content-sec-ul li").on('click',function() {
     let parent = $(this).parent();
     if ($(this).hasClass('background-color-blue')){
          parent.find("li").removeClass('background-color-blue');
          $(this).siblings("input[name='tagMxId[]']").val('');
     }else{
         parent.find("li").removeClass('background-color-blue');
         $(this).addClass('background-color-blue');
         let id = $(this).data('id');
         $(this).siblings("input[name='tagMxId[]']").val(id);
     }
   
     set_label_num();
 })
 //重置标签
 $("#reset").on('click',function (){
     $(".label-content-sec-ul").find("li").removeClass('background-color-blue');
     $(".label-content-sec-ul").find("input[type='hidden']").val('');
     set_label_num();
 })
</script>
efo;

        return $this->layer(array("title" => $addLabelWord, "height" => 700, "width" => 900, "html" => $html, "button" => false));
    }

    /**
     * 批量添加标签编辑
     */
    public function batchAddTagsEdit(): bool|string
    {
        $listId = $this->post('listId');
        $tagMxId = $this->post('tagMxId');//标签ID
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('client.batchAddTagsEdit.power');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('client.batchAddTagsEdit.noClient');
        } elseif (empty($tagMxId) || !is_array($tagMxId)) {
            $json['warn'] = L('client.batchAddTagsEdit.noLabel');
        } else {
            $x=0;
            $text = '';
            foreach ($listId as $khid) {
                $kehu = query(self::table, "khid = '$khid'");
                if (!in_array($this->control['stid'], explode(",", $kehu['see']))) {
                    $text .= str_replace(['{{companyName}}'], [$kehu['companyName']], L('client.batchAddTagsEdit.notYours'))."<br>";
                } else {
                    $x++;
                    $tagsText = '';
                    //添加标签
                    $kehu_label_id = [];
                    foreach ($tagMxId as $tagsId) {
                        $kehu_label = query('kehu_label', "targetId = '$kehu[khid]' and tag_detail_id = '$tagsId'");
                        $tags_detail = query('tag_detail', "id = '$tagsId'");
                        $tags = query('tag', "id = '$tags_detail[orderId]'");
                        $tagsText .= $tags_detail['name'] . ',';
                        if (empty($kehu_label['id'])) {
                            $mid = self::getId();
                            $kehu_label_id[] = $mid;
                            static::insert(array(
                                'table' => 'kehu_label',
                                'field' => [
                                    'id' => $mid,
                                    'coid'=>self::$coid,
                                    'targetId' => $kehu['khid'],
                                    'tag_detail_id' => $tagsId,
                                    'tagId' => $tags['id'],
                                    'type' => 1,
                                    'time' => $this->time,
                                ]
                            ));
                        } else {
                            $kehu_label_id[] = $kehu_label['id'];
                        }
                    }
                    //删除无效关联的标签
                    delete(array('table' => 'kehu_label', 'where' => "id not in ('" . implode("','", $kehu_label_id) . "') and targetId = '$kehu[khid]'"));
                    update(array('table' => self::table, 'field' => ['tags' => $tagsText], 'where' => "khid = '$kehu[khid]'"));
                    $text .= str_replace(['{{companyName}}','{{tagsText}}'], [$kehu['companyName'],$tagsText], L('client.batchAddTagsEdit.text'))."<br>";
                }
            }
            $this->logText(["type" => self::page, "text" => str_replace(['{{staffName}}'], [$this->control['name']], L('client.batchAddTagsEdit.log')).$text]);
            $json['warn'] = 2;
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('client.batchAddTagsEdit.warn'));

        }
        return json_encode($json, 320);
    }


    /**
     * 地图选址
     */
    public function map(): bool|string
    {
        $key = para('tencentMapKey');

        $sureWord = L('client.map.sure');
        $addressSelectionWord = L('client.map.addressSelection');
        $html = <<<efo
<iframe id="mapPage" width="100%" height="90%" frameborder=0
    src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key={$key}&referer=myapp">
</iframe>
<div style="text-align: center;padding: 10px"><input onclick="$('#clientMap').hide()" class="button" type="button" value="$sureWord"></div>
<script>
    window.addEventListener('message', function(event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data;
        if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
            //移除监听
           event.stopPropagation();
           convertRegion(loc.latlng.lat+','+loc.latlng.lng)
          $("[name='location']").val(loc.latlng.lat+','+loc.latlng.lng);
          $("[name='address']").val(loc.poiaddress);
        }
    }, false);
</script>
efo;

        return $this->layer(array("title" => $addressSelectionWord, "height" => 800, "width" => 1000, "html" => $html, "button" => false));
    }

    /**
     * 获取默认公客池ID
     * @return mixed
     */
    public static function defaulPoolId(){
        return query('pool',"type='公客池' and coid='".self::$coid."' and isDefault = 1")['id'];
    }
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $labelMxId = $this->post('labelMxId');//标签ID
        $field = [
            "contactName" => $this->post('contactName'),//联系人姓名
            "contactIdentity" => $this->post('contactIdentity'),//联系人身份
            "contactTel" => $this->post('contactTel'),//联系人手机号码
            "contactQQ" => $this->post('contactQQ'),//联系人QQ号码
            "contactWx" => $this->post('contactWx'),//联系人微信号
            "address" => $this->post('address'),
            "birthDay" => $this->post('birthDay'),
            "website" => $this->post('website'),
            "email" => $this->post('email'),
            "nature" => $this->post('nature'),
            "invoiceCompany" => $this->post('invoiceCompany'),
            "postAddress" => $this->post('postAddress'),
            "workFlow" => $this->post('workFlow'),//跟进状态
            "source" => $this->post('source'),//客户来源
            "level" => $this->post('level'),
            "classify" => $this->post('classify'),
            "scale" => $this->post('scale'),
            'followTime' => $this->post('followTime'),
            "industry" => $this->post('industry'),//所在行业
            "text" => $this->post('text'),
            "companyName" => $this->post('companyName'),//公司名称
            "companyNum" => $this->post('companyNum'),//纳税人识别号
            "companyBank" => $this->post('companyBank'),//公司开户银行
            "companyBankNum" => $this->post('companyBankNum'),//对公账号
            "landline" => $this->post('landline'),//公司座机
            "companyAddress" => $this->post('companyAddress'),//开票地址
            'invoiceType' => $this->post('invoiceType'),
            "taxRate" => (float)$this->post('taxRate')/100,
            "payType" => $this->post('payType'),
            "credits" => $this->post('credits'),
            "settleType" => $this->post('settleType'),
            "checkDay" => $this->post('checkDay'),
            'poolId' => $this->post('poolId') ?: self::defaulPoolId(),
            'manager' => $this->post('manager'),
            'region' => $this->post('region'),
            'freight' => $this->post('freight'),
            'collaborator' => $this->post('collaborator') && is_array($this->post('collaborator')) ? implode(',', array_unique($this->post('collaborator'))) : '',
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        ];
        $annotation = [
            'companyName' => L('client.editEdit.companyName'),
            'nature' => L('client.editEdit.nature'),
            "contactTel" => L('client.editEdit.contactTel'),
            'manager' => L('client.editEdit.manager'),
        ];
        $rules = [
            'companyName' => 'required',
            'nature' => 'required',
            'manager' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        // 收货地址
        $type = 'address';
        $addrField = [
            'id' => $this->post($type . 'id'),
            'coid' => self::$coid,
            'orderId' => $id,
            'name' => $this->post($type . 'name'),
            'tel' => $this->post($type . 'tel'),
            'address' => $this->post($type . 'address'),
            'time' => $this->time,
        ];

        $where = " khid = '$id' ";
        $info = query(self::table, $where);
        //重复检查
        $setItem = ['companyName' => ['companyName'=>'公司名称'], 'contactName' => ['contactName'=>'常用联系人']];
        $optionSetting = optionSettingClass::getSetting('公共');  //选项设置
        $companyRepeatItemCtrl = $optionSetting['companyRepeatItemCtrl'];  //重复检查项
        $checkItem = [];
        foreach ($companyRepeatItemCtrl as $val){
            $checkItem = array_merge($checkItem,($setItem[$val] ?? []));
        }
        $repeat = array(
            "khid" => $id,
            "field" => $field,
            //"name" => array("contactTel" => "联系人手机号码", "contactQQ" => "联系人QQ", "companyName" => "公司名称", "companyNum" => "纳税人识别号"),
            "name" => $checkItem,
        );
        $warn = $this->repeat($repeat);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('client.editEdit.power');
        } elseif (!empty($field['email']) && preg_match(checkEmail, $field['email']) == 0) {
            $json['warn'] = L('client.editEdit.emailError');
        } elseif (!empty($field['contactQQ']) && preg_match(checkInteger, $field['contactQQ']) == 0) {
            $json['warn'] = L('client.editEdit.qqError');
        } elseif (!empty($field['website']) && preg_match(checkUrl, $field['website']) == 0) {
            $json['warn'] = L('client.editEdit.websiteError');
        } elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
            $json['warn'] = L('client.editEdit.collaboratorError');
        } elseif (!empty($info['khid']) && !in_array($this->control['stid'], explode(",", $info['see']))) {
            $json['warn'] = L('client.editEdit.notYours');
        } elseif (static::total(array('table' => self::table, 'where' => "companyName = '$field[companyName]' and khid !='$id'")) > 0) {
            $json['warn'] = L('client.editEdit.nameRepeat');
        } elseif ($warn && $optionSetting['companyRepeatCtrl'] == '禁止') {
            $json['warn'] = $warn;
        } else {
            //查看范围
            $field['see'] = implode(',', array_filter(array_unique(array_merge(explode(',', $field['collaborator']), [$field['manager']]))));
            // 经纬度及地区处理
            if ($this->post('location')){
                $location = explode(',', $this->post('location'));
                $field['lat'] = $location[0];
                $field['lng'] = $location[1];
                if(empty($field['region'])) {
                    $region = componentClass::coordinateToAddr($field['lat'], $field['lng']);
                    if ($region['err_code'] == 0) {
                        $field['region'] = $region['data']['address_component']['province'] . '-' . $region['data']['address_component']['city'] . '-' . $region['data']['address_component']['district'];
                    }
                }
            }
            $this->startTrans();
            if (!$info['khid']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'C',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field).rand(1,99);
                $field = array_merge($field, [
                    'khid' => $id,
                    'coid'=>self::$coid,
                    'orderNo'=>$userNo,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);

                $post_data = [
                    'no' => $userNo,
                    'name' => $field['contactName'],
                    'contacts' => $field['contactName'],
                    'phone' => $field['contactTel'],
                    'cartno' => '',
                    'addr' => $field['address'],
                    'loglat' => '',
                    'remark' => $field['text'],
                ];
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $post_data = [
                    'id' => $info['id'],
                    'no' => $info['orderNo'],
                    'name' => $field['contactName'],
                    'contacts' => $field['contactName'],
                    'phone' => $field['contactTel'],
                    'cartno' => '',
                    'addr' => $field['address'],
                    'loglat' => '',
                    'remark' => $field['text'],
                ];
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //上传旭永-客户
                $tokenData = $this->getToken();
                if(!$tokenData['code']){
                    $json['warn'] = $tokenData['msg'];
                    $this->rollback();
                    goto resp;
                }
//                $customerEdit = $this->send_post("txhg/customerList",[
//                    'startDate'=>'2020-01-01',
//                    'endDate'=>'',
//                    'pageNum'=>'1',
//                    'pageSize'=>'10',
//                ],$tokenData['data']);
//                var_dump($customerEdit);die;
                $customerEdit = $this->send_post("txhg/customerEdit",$post_data,$tokenData['data']);
                if($customerEdit['code'] !== '1'){
                    $json['warn'] = "上传接口返回失败；失败原因：".$customerEdit['msg'];
                    $this->rollback();
                    goto resp;
                }

                $tagsText = '';
                //添加标签
                $kehu_label_id = [];
                if (!empty($labelMxId) && is_array($labelMxId)) {
                    foreach ($labelMxId as $tagsId) {
                        $kehu_label = query('kehu_label', "targetId = '$id' and tag_detail_id = '$tagsId'");
                        $tags_detail = query('tag_detail', "id = '$tagsId'");
                        $tags = query('tag', "id = '$tags_detail[orderId]'");
                        $tagsText .= $tags_detail['name'] . ',';
                        if (empty($kehu_label['id'])) {
                            $mid = self::getId();
                            $kehu_label_id[] = $mid;
                            static::insert(array(
                                'table' => 'kehu_label',
                                'field' => [
                                    'id' => $mid,
                                    'coid'=>self::$coid,
                                    'targetId' => $id,
                                    'tag_detail_id' => $tagsId,
                                    'tagId' => $tags['id'],
                                    'type' => 1,
                                    'time' => $this->time,
                                ]
                            ));
                        } else {
                            $kehu_label_id[] = $kehu_label['id'];
                        }
                    }
                }
                //删除无效关联的标签
                delete(array('table' => 'kehu_label', 'where' => "id not in ('" . implode("','", $kehu_label_id) . "') and targetId = '$id'"));
                update(array('table' => self::table, 'field' => ['tags' => $tagsText,'id'=>$customerEdit['data']['ID']], 'where' => "khid = '$id'"));
                //常用联系人添加到联系人中
                if (!empty($field['contactName']) && !empty($field['contactTel'])){
                    $contact  =query('kehu_staff',"khid = '$id' and tel = '$field[contactTel]'");
                    if (empty($contact['id'])){
                        static::insert(array(
                            'table'=>'kehu_staff',
                            'field'=>[
                                'id'=>suiji(),
                                'khid'=>$id,
                                'coid'=>self::$coid,
                                'stid'=>self::$stid,
                                "name" => $field['contactName'],//姓名
                                "tel" => $field['contactTel'],//手机
                                "qq" => $field['contactQQ'],//QQ号码
                                "WeChat" => $field['contactWx'],//微信号
                                "text" => '常用联系人',//备注
                            ]
                        ));
                    }else{
                        static::update(array(
                            'table'=>'kehu_staff',
                            'field'=>[
                                "name" => $field['contactName'],//姓名
                                "tel" => $field['contactTel'],//手机
                                "qq" => $field['contactQQ'],//QQ号码
                                "WeChat" => $field['contactWx'],//微信号
                                "text" => '常用联系人',//备注
                            ],
                            'where'=>"id = '$contact[id]'"
                        ));
                    }
                }

                /*if (is_array($addrField)) {
                    $checkAddressKey = ['name','tel','address'];
                    static::insertArray(self::tableAddr, $addrField, emptyFilter: $checkAddressKey);
                    if (!empty(current($addrField))) {
                        delete(['table' => self::tableAddr, 'where' => " id NOT IN ('" . implode("','", current($addrField)) . "') AND orderId = '$id'  "]);
                    }
                }*/
                $this->commitTrans();

                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('client.editEdit.log'));
                $this->logWrite($id, $type);
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }else{
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }




    /*客户查看权限*/
    public function clientSee($khid)
    {
        //数据库查询
        $kehu = query("kehu", " khid = '$khid' ");
        //验证
        if (empty($khid)) {
            $json['warn'] = L('client.clientSee.idEmpty');
        } elseif (empty($kehu['khid'])) {
            $json['warn'] = L('client.clientSee.empty');
        } elseif (!$this->power("client", "seeAll")) {
            //不是公客，又没有查看所有客户的权限
            if (!$this->power("client", "see")) {
                //有查看自己客户的权限
                $json['warn'] = L('client.clientSee.power');
            } elseif (!in_array($this->control['stid'], explode(",", $kehu['see']))) {
                $json['warn'] = L('client.clientSee.notYours');
            } else {
                $json['warn'] = "";
            }
        } else {
            $json['warn'] = "";
        }
        if (empty($json['warn'])) {
            $json = $kehu;
        }
        //返回
        return $json;
    }

    /*客户管理-客户详情页*/
    public function detail()
    {
        $kehu = $this->clientSee($this->get('id'));
        if (!empty($kehu['warn'])) {
            $html = $kehu['warn'];
        } else {
            //数据准备
            $pool = query('pool', " id = '$kehu[poolId]'");
            //菜单
            $data = array(
                "id" => $kehu['khid'],
                "title" => kong($kehu['companyName']),
                "menu" => array(
                    "detail" => L('client.detail.detail'),
                    "contacts" => L('client.detail.contacts').'(收货信息)',
                    "visit" => L('client.detail.visit'),
                    "file" => array("name" => L('client.detail.file'), "cla" => "file", "fun" => "clientFile"),
                    "record" => array("name" => L('client.detail.record'), "cla" => "follow", "fun" => "clientRecord"),
                    "contract" => array("name" => "合同", "cla" => "salesContract", "fun" => "clientContract"),
                    "saleOrder" => array("name" => "销售订单", "cla" => "saleOrder", "fun" => "clientOrder"),
                    "saleSend" => array("name" => "销售发货", "cla" => "saleSendOrder", "fun" => "clientSendOrder"),
                    "saleRefund" => array("name" => "销售退货", "cla" => "saleRefundOrder", "fun" => "clientRefundOrder"),
                    "income" => array("name" => "收款记录", "cla" => "inReceipt", "fun" => "clientIn"),
                    "invoice" => array("name" => "开票记录", "cla" => "saleInvoice", "fun" => "clientInvoice"),
                    "clientPrice" => array("name" => "价格本", "cla" => "clientPriceList", "fun" => "clientPrice"),
                    "aftermarket" => array("name" => "售后记录", "cla" => "aftermarketRecord", "fun" => "aftermarket"),
                    "business" => array("name" => L('client.detail.business'), "cla" => "opportunity", "fun" => "clientOpt"),
                    "price" => array("name" => L('client.detail.price'), "cla" => "quotations", "fun" => "clientQuo"),
                    //"chat" => "会话存档",
                    "log" =>  L('client.detail.operateLog'),
                )
            );
            //按钮
            $button = [];
            if ($this->power("client", "edit") and self::$stid == $kehu['manager']) {
                //按钮
                $button[] = [
                    "name" => L('client.detail.edit'),
                    "type" => "顶部页卡",
                    "title" => L('client.detail.edit'),
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $kehu['khid'],
                    'style' => 'li-btn-blue-bg',
                ];
                //按钮
                $button[] = [
                    "name" => L('client.detail.transfer'),
                    "type" => "点击事件",
                    "title" => L('client.detail.transfer'),
                    'fun' => "layer('" . self::page . "','transfer',{id:'" . $kehu['khid'] . "'})",
                ];
                //按钮
                $button[] = [
                    "name" => L('client.detail.transferPool'),
                    "type" => "点击事件",
                    "title" => L('client.detail.transferPool'),
                    'fun' => "layer('" . self::page . "','pool',{id:'" . $kehu['khid'] . "'})",
                ];
            }
            if ($this->power(self::page, "del") and self::$stid == $kehu['manager']) {
                //按钮
                $button[] = [
                    "name" => L('client.detail.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $kehu['khid']],
                ];
            }

            /******标签*********/
            $tags = '';
            $kehu_label = find(array('table' => 'kehu_label', 'where'=>"targetId = '$kehu[khid]' order by list asc"));
            foreach ($kehu_label['array'] as $array) {
                $tag_detail = query('tag_detail', "id = '$array[tag_detail_id]'");
                $tags .= "<span class='background-color-gray' style='margin-right: 5px'>{$tag_detail['name']}</span>";
            }
            /*// 收货地址
            $addTr[] = [L('salesContract.editPage.name'), L('salesContract.editPage.tel'), L('salesContract.editPage.address')];
            $result = find(['table' => self::tableAddr . " where orderId = '{$kehu['khid']}' order by time DESC"]);
            foreach ((array)$result['array'] as $array) {
                $addTr[] = [
                    $array['name'], $array['tel'], $array['address'],
                ];
            }
            $addrTab = $this->listTable(["tr" => $addTr, 'showSort' => true]);*/
            $data['button'] = $this->tableShowButton($button);
            //生成表单
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        L('client.edit.companyName') => $kehu['companyName'],
                        L('client.edit.nature') => $kehu['nature'],
                        L('client.edit.contactName') => $kehu['contactName'],
                    ),
                    array(
                        L('client.edit.contactIdentity') => $kehu['contactIdentity'],
                        L('client.edit.contactTel') => $kehu['contactTel'],
                        L('client.edit.landline') => $kehu['landline'],
                    ),
                    array(
                        L('client.edit.contactWx') => $kehu['contactWx'],
                        L('client.edit.contactQQ') => $kehu['contactQQ'],
                        L('client.edit.birthDay') => self::null($kehu['birthDay']),
                    ),
                    array(
                        L('client.edit.website') => $kehu['website'],
                        L('client.edit.email') => $kehu['email'],
                        L('client.edit.address') => $kehu['address'],
                    ),
                    array(
                        "单次运费" => $kehu['freight'],
                    ),
                ),
                L('client.edit.manageInfo') => array(
                    array(
                        L('client.edit.level') => $kehu['level'],
                        L('client.edit.classify') => $kehu['classify'],
                        L('client.edit.industry') => $kehu['industry'],
                        L('client.edit.scale') => $kehu['scale'],
                    ),
                    array(
                        L('client.edit.source') => $kehu['source'],
                        L('client.edit.tags') => $tags,
                        L('client.edit.workFlow') => $kehu['workFlow'],
                        L('client.edit.followTime') => self::null($kehu['followTime']),
                    ),
                    array(
                        L('client.edit.pool') => clueClass::setBackGroundColorGray($pool['name']),
                        L('client.edit.manager') => self::findStaff($kehu['manager']),
                        L('client.edit.collaborator') => clueClass::showMember($kehu['collaborator']),
                    ),
                    array(
                        L('client.edit.remark') => pre($kehu['text']),
                    ),
                ),
                L('client.edit.invoice') => array(
                    array(
                        "发票类型" => $kehu['invoiceType'],
                        "默认税率" => ($kehu['taxRate']*100).'%',
                        "默认付款方式" => $kehu['payType'],
                        "信用额度（".static::$unit."）" => $kehu['credits'],
                    ),
                    array(
                        "默认结算方式" => $kehu['settleType'],
                        "对账日" => $kehu['checkDay'],
                        L('client.edit.invoiceCompany') => $kehu['invoiceCompany'],
                        L('client.edit.companyBank') => $kehu['companyBank'],
                    ),
                    array(
                        L('client.edit.companyBankNum') => $kehu['companyBankNum'],
                        L('client.edit.companyAddress') => $kehu['companyAddress'],
                        L('client.edit.companyNum') => $kehu['companyNum'],
                        L('client.edit.postAddress') => $kehu['postAddress'],
                    ),
                ),
                L('client.detail.sys') => array(
                    array(
                        L('client.detail.stid') => self::findStaff($kehu['stid']),
                        L('client.detail.time') => $kehu['time'],
                        L('client.detail.updateTime') => $kehu['updateTime'],
                    ),
                ),
            ));
            /*$data['html'] .= $this->detailList([
                'title' => L('salesContract.editPage.shippingAddress'),
                'html' => $addrTab,
            ]);*/
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    /**
     * 转到客户池
     */
    public function pool()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('client.pool.clientPool')."：" => selectMultiple(array('table' => 'pool', 'where' => "type = '公客池' and coid='".self::$coid."'", "title" => L('client.pool.choice'), 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'poolId')),
            ),
        )
        ));
        //返回
        return $this->layer(array("title" => L('client.pool.transferToClientPool'), 'winFix' => true, "height" => 200, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     *  转到客户池编辑
     */
    public function poolEdit()
    {
        $listId = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $poolId = $this->post('poolId');
        $pool = query('pool', "id = '$poolId'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('client.poolEdit.power');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('client.poolEdit.emptyClient');
        } elseif (empty($pool['id'])) {
            $json['warn'] = L('client.poolEdit.empty');
        } else {
            $x = 0;
            foreach ($listId as $id) {
                //客户
                $info = query(self::table, " khid = '$id'");
                if ($info['manager'] == self::$stid) {
                    $warn = update(array(
                        'table' => self::table,
                        'field' => [
                            'poolId' => $pool['id'],
                        ],
                        'where' => "khid = '$id'"
                    ));
                    if (in_array($warn, ['新增成功', '更新成功'])) {
                        $x++;
                        $text = str_replace(['{{staffName}}','{{companyName}}','{{id}}','{{pool}}'], [$this->control['name'],$info['companyName'],$id,$pool['name']], L('client.poolEdit.logText'));
                        $this->logText(["type" => self::page, "text" => $text]);
                        //日志
                        $this->logWrite($id, '添加到客户池', str_replace(['{{staffName}}','{{pool}}'], [$this->control['name'],$pool['name']], L('client.poolEdit.logWrite')));
                    }
                } else {
                    $text = str_replace(['{{staffName}}','{{companyName}}'], [$this->control['name'],$info['companyName']], L('client.poolEdit.failLog'));
                    $this->logText(["type" => self::page, "text" => $text]);
                }

            }
            $json['warn'] = 2;
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('client.poolEdit.warn'));
        }
        return json_encode($json, 320);
    }

    /**
     * 转交
     */
    public function transfer()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('client.transfer.manager')."：" => selectMultiple(array("title" => L('client.transfer.choice'), 'option' => $this->staffOption(), 'name' => 'manager')),
            ),
            array(
                L('client.transfer.collaborator')."：" => selectMultiple(array('table' => 'staff', 'multiple' => true, "title" => L('client.transfer.choice'), 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'collaborator[]')),
            ),

        )
        ));
        //返回
        return $this->layer(array("title" => L('client.transfer.transmit'), 'winFix' => true, "height" => 260, "html" => $html, 'formTwo' => 'listForm,allClueForm'));
    }

    /**
     * 获取转交给他人的选项
     * @return array
     */
    public function staffOption(): array
    {
        $option=[];
        $result = find(array('table' => 'staff', 'where' => "state in ('试用','转正')"));
        foreach ($result['array'] as $array) {
            $option[$array['stid']] = $array['name'];
        }
        return $option;
    }


    /**
     * 转交编辑
     */
    public function transferEdit(): bool|string
    {
        $listId = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $field = array(
            'manager' => $this->post('manager'),
            'collaborator' => $this->post('collaborator') && is_array($this->post('collaborator')) ? implode(',', array_unique($this->post('collaborator'))) : '',
        );
        if (!$this->power(self::page, 'edit') && !$this->power('allClient', 'edit')) {
            $json['warn'] = L('client.transferEdit.power');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('client.transferEdit.notFindClient');
        } elseif (empty($this->post('manager'))) {
            $json['warn'] = L('client.transferEdit.choiceManage');
        } elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
            $json['warn'] = L('client.transferEdit.choiceError');
        } else {
            $x = 0;
            //查看范围
            $field['see'] = implode(',', array_unique(array_filter(array_merge([$field['manager']], explode(',', $field['collaborator'])))));
            $field['collaborator'] = empty($field['manager']) ? '' : $field['collaborator'];
            $manager = query('staff', "stid = '$field[manager]'");
            foreach ($listId as $id) {
                $info = query(self::table, " khid = '$id'");
                if ($info['manager'] != $field['manager'] && ($info['manager'] == self::$stid || $this->power(self::page,'admin') || $this->power('allClient', 'edit'))) {
                    $warn = update(array(
                        'table' => self::table,
                        'field' => $field,
                        'where' => " khid = '$id'"
                    ));
                    if ($warn == '更新成功') {
                        $x++;
                        $this->logWrite($id, '转交',str_replace(['{{staffName}}','{{companyName}}','{{manage}}'], [$this->control['name'],$info['companyName'],$manager['name']], L('client.transferEdit.logText')));
                        $text = str_replace(['{{staffName}}','{{companyName}}','{{id}}','{{manage}}'], [$this->control['name'],$info['companyName'],$id,$manager['name']], L('client.transferEdit.log'));

                        $this->logText(["type" => self::page, "text" => $text]);
                    }
                } else {
                    $text = str_replace(['{{staffName}}','{{companyName}}'], [$this->control['name'],$info['companyName']], L('client.transferEdit.failLog'));
                    $this->logText(["type" => self::page, "text" => $text]);
                }
            }
            $json['warn'] = 2;
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('client.transferEdit.warn'));
        }
        return json_encode($json, 320);
    }

    /*客户管理-客户列表-联系人*/
    public function contacts()
    {
        $edit=$del = '';
        if ($this->power(self::page, "staffEdit")) {
            $edit = "<span class='spanButton' title='".L('client.contacts.newContacts')."' onclick=\"layer('" . self::page . "','staff',{id:'" . suiji() . "',clientId:'" . $this->get('id') . "'})\">".L('client.contacts.new')."</span>\n";
        }
        if ($this->power(self::page, "staffDel")) {
            $del = "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'delContact'})\">".L('client.contacts.del')."</span>\n";
        }
        $checkAll = $this->checkAll("clientContactsForm", "clientStaffId");
        $tr[] = array($checkAll, L('client.contacts.name'), L('client.contacts.sex'), L('client.contacts.position'), L('client.contacts.tel'), L('cluePool.detail.email'), L('client.contacts.phone'), L('client.contacts.WeChat'), L('client.contacts.qq'), L('client.contacts.birthDay'), L('client.contacts.address'), L('client.contacts.text'), L('client.contacts.updateTime'));
        $sql = find(array("table" => "kehu_staff", "where" => " khid = '" . $this->get('id') . "' order by updateTime desc "));
        foreach ($sql['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "clientStaffId", "value" => $array['id']),
                "edit" => array("title" =>L('client.contacts.edit'), "click" => "layer('" . self::page . "','staff',{id:'" . $array['id'] . "'})"),
            );
            $tr[] = array($this->dominate($dominate), $array['name'], $array['sex'], $array['position'], $array['tel'], $array['email'], $array['phone'], $array['WeChat'], $array['qq'], self::null($array['birthDay']), $array['address'], $array['text'], $array['updateTime']);
        }
        $json['html'] = "<div class='p-10'>".$edit . $del.space."<form name='clientContactsForm'>" . $this->tableMany(array("tr" => $tr,"displayFields" => false)) . "</form></div>";
        return json_encode($json, 320);
    }

    /*客户管理-客户列表-编辑联系人*/
    public function staff()
    {
        $hidden='';
        $kehuStaff = query("kehu_staff", " id = '" . $this->post('id') . "' ");
        if (empty($this->post('id'))) {
            $html = L('client.staff.idEmpty');
        } elseif (empty($kehuStaff['id'])) {
            $kehu = query("kehu", " khid = '" . $this->post('clientId') . "' ");
            $hidden = hidden(array("name" => "clientId", "value" => $kehu['khid']));
        }
        if (empty($html)) {
            $html = $this->layerEdit(array("table" => array(
                array(
                    must . L('client.contacts.name')."：" => text(array("name" => "name", "class" => "text", "value" => $kehuStaff['name'])),
                    must . L('client.contacts.sex')."：" => radio(array("name" => "sex", 'value' => ['男', '女'], "checked" => $kehuStaff['sex'])),
                ),
                array(
                    L('client.contacts.department')."：" => text(array("name" => "department", "class" => "text", "value" => $kehuStaff['department'])),
                    L('client.contacts.position')."：" => text(array("name" => "position", "class" => "text", "value" => $kehuStaff['position'])),
                ),
                array(
                    L('client.contacts.tel')."：" => text(array("name" => "tel", "class" => "text", "value" => $kehuStaff['tel'])),
                    L('cluePool.detail.email')."：" => text(array("name" => "email", "class" => "text", "value" => $kehuStaff['email'])),
                ),
                array(
                    L('client.contacts.phone')."：" => text(array("name" => "phone", "class" => "text", "value" => $kehuStaff['phone'])),
                    L('client.contacts.WeChat')."：" => text(array("name" => "WeChat", "class" => "text", "value" => $kehuStaff['WeChat'])),
                ),
                array(
                    L('client.contacts.qq')."：" => text(array("name" => "qq", "class" => "text textPrice", "value" => $kehuStaff['qq'])),
                    L('client.contacts.birthDay')."：" => text(array("name" => "birthDay", "class" => "text", 'laydate' => [], "value" => self::null($kehuStaff['birthDay'], false))),
                ),
                array(
                    L('client.contacts.address')."：" => text(array("name" => "address", "class" => "text", "value" => $kehuStaff['address'])),
                ),
                array(
                    L('client.contacts.text')."：" => textarea(array("name" => "text", "class" => "textarea", "value" => $kehuStaff['text'])),
                )
            ), "hidden" => $hidden));
        }
        return $this->layer(array("title" => L('client.staff.editContacts'), "height" => 450, "width" => 800, "html" => $html));
    }

    /*客户管理-客户列表-联系人-编辑*/
    public function staffEdit()
    {
        //赋值
        $field = array(
            "sex" => $this->post('sex'),
            "position" => $this->post('position'),//职位
            "name" => $this->post('name'),//姓名
            "department" => $this->post('department'),
            "birthDay" => $this->post('birthDay'),
            "tel" => $this->post('tel'),//手机
            "email" => $this->post('email'),//邮箱
            "phone" => $this->post('phone'),//座机
            "qq" => $this->post('qq'),//QQ号码
            "WeChat" => $this->post('WeChat'),//微信号
            "address" => $this->post('address'),//排序号
            "text" => $this->post('text'),//备注
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        );
        //数据库查询
        $kehuStaff = query("kehu_staff", " id = '" . $this->post('id') . "' ");
        if (empty($kehuStaff['khid'])) {
            $kehu = query("kehu", " khid = '" . $this->post('clientId') . "' ");
            if (empty($this->post('clientId'))) {
                $json['warn'] = L('client.staffEdit.idEmpty');
            } elseif (empty($kehu['khid'])) {
                $json['warn'] = L('client.staffEdit.empty');
            }
        } else {
            $kehu = query("kehu", " khid = '$kehuStaff[khid]' ");
        }
        //判断
        if (!$this->power("client", "staffEdit")) {
            $json['warn'] = L('client.staffEdit.power');
        } elseif (empty($field['name'])) {
            $json['warn'] = L('client.staffEdit.name');
        } elseif (empty($field['sex'])) {
            $json['warn'] = L('client.staffEdit.sex');
        } /*elseif (empty($field['tel'])) {
            $json['warn'] = L('client.staffEdit.tel');
        } elseif (preg_match(checkTel, $field['tel']) == 0) {
            $json['warn'] = L('client.staffEdit.telError');
        } */elseif (!empty($field['tel']) && sqlNum("kehu_staff", " tel = '$field[tel]' and khid = '$kehu[khid]' and id != '" . $this->post('id') . "' ") > 0) {
            $json['warn'] = L('client.staffEdit.telRepeat');
        } elseif (!empty($field['qq']) and preg_match(checkInteger, $field['qq']) == 0) {
            $json['warn'] = L('client.staffEdit.qqError');
        } elseif (empty($kehuStaff['id'])) {
            $field = array_merge($field, array("id" => $this->post('id'),  'coid'=>self::$coid,"stid" => $this->control['stid'], "khid" => $this->post('clientId'), "time" => date("Y-m-d H:i:s")));
            $json['warn'] = insert(array("table" => "kehu_staff", "field" => $field));
        } else {
            $json['warn'] = update(array("table" => "kehu_staff", "field" => $field, "where" => " id = '$kehuStaff[id]' "));
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = str_replace(['{{staffName}}','{{companyName}}','{{khid}}','{{type}}','{{name}}'], [$this->control['name'],$kehu['companyName'],$kehu['khid'],$type,$field['name']], L('client.staffEdit.log'));
            $this->logText(array("type" => "client", "text" => $text));
            //返回
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=client&fun=detail&menu=contacts&id=" . $kehu['khid'];
        return json_encode($json, 320);
    }

    /*客户资料排重*/
    public function repeat($data)
    {
        foreach ($data['name'] as $name => $explain) {
            if (!empty($data['field'][$name])) {
                //客户排重查询
                $kehu = query("kehu", $name . " = '" . $data['field'][$name] . "' and khid != '$data[khid]' and coid = '".self::$coid."' ");
                if (!empty($kehu['khid'])) {
                    return str_replace(['{{companyName}}','{{explain}}','{{name}}'], [$kehu['companyName'],$explain,$data['field'][$name]], L('client.repeat.warn'));
                }
            }
        }
        return false;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            case 'delContact':
                $act = 'staffDel';
                $msg = L('client.operate.delContact');
                $title = 'clientContactsDelete';
                $function = 'contactsDelete';
                $form = self::page . 'OperateForm, clientContactsForm';

                break;
            default:
                $act = 'del';
                $msg = L('client.operate.delclient');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('client.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('client.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('client.delete.noChoice');
        } else {
            $this->startTrans();
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " khid = '$id' ");
                if ($info['manager'] != self::$stid) {
                    //返回
                    $warn = L('client.delete.notYours');
                }elseif(static::total(array('table'=>'opportunity','where'=>"khid = '$id'")) >0){
                    $warn ="已有商机使用，不能删除";
                }elseif(static::total(array('table'=>'quotations','where'=>"khid = '$id'")) >0){
                    $warn ="已有报价单使用，不能删除";
                }elseif(static::total(array('table'=>'sales_contract','where'=>"clientId = '$id'")) >0){
                    $warn ="已有销售合同使用，不能删除";
                }elseif(static::total(array('table'=>'sale_order','where'=>"khid = '$id'")) >0){
                    $warn =L('client.delete.usedSale');
                } elseif(static::total(array('table'=>'sale_send_order','where'=>"khid = '$id'")) >0){
                    $warn =L('client.delete.usedSaleSend');
                }elseif(static::total(array('table'=>'sale_refund_order','where'=>"khid = '$id'")) >0){
                    $warn =L('client.delete.usedSaleReturn');
                } else {
                    $result = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($result['array'] as $file) {
                        fileDelete($file['src']);
                    }
                    //删除附件
                    delete(array("table" => "file", "where" => " targetId = '$id' "));
                    //删除标签
                    delete(array("table" => "kehu_label", "where" => " targetId = '$id' "));
                    //删除跟进记录
                    delete(array("table" => "follow", "where" => " targetId = '$id' "));
                    //删除操作日志
                    delete(array("table" => "clue_log", "where" => " orderId = '$id' "));
                    //删除客户联系人
                    delete(array("table" => "kehu_staff", "where" => " khid = '$id' "));
                    //删除拜访记录
                    delete(array("table" => "visit_plan", "where" => " khid = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " khid = '$id' "));
                    //删除旭永-客户
                    $tokenData = $this->getToken();
                    if(!$tokenData['code']){
                        $json['warn'] = $tokenData['msg'];
                        $this->rollback();
                        goto resp;
                    }
                    $customerEdit = $this->send_post("txhg/customerDelete",['id'=>$info['id']],$tokenData['data']);
                    if($customerEdit['code']!== 1){
                        $json['warn'] = "上传接口返回失败；失败原因：".$customerEdit['msg'];
                        $this->rollback();
                        goto resp;
                    }
                    //返回
                    $warn = L('client.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{khid}}'], [$info['khid']], L('client.delete.text')) . $warn . "<br>";
            }
            $this->commitTrans();
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('client.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('client.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        resp:
        return json_encode($json, 320);
    }

    /*客户管理-客户列表-联系人-批量删除*/
    public function contactsDelete(): bool|string
    {
        if (!$this->power("client", "staffDel")) {
            $json['warn'] = L('client.contactsDelete.power');
        } elseif (empty($this->post('clientStaffId'))) {
            $json['warn'] = L('client.contactsDelete.noChoice');
        } else {
            $x = 0;
            foreach ($this->post('clientStaffId') as $id) {
                $kehuStaff = query("kehu_staff", " id = '$id'");
                $kehu = query("kehu", " khid = '$kehuStaff[khid]' ");
                //删除客户联系人基本参数
                delete(array("table" => "kehu_staff", "where" => " id = '$id' "));
                //添加日志
                $text = str_replace(['{{staffName}}','{{companyName}}','{{position}}','{{name}}','{{tel}}'], [$this->control['name'],kong($kehu['companyName']),$kehuStaff['position'],$kehuStaff['name'],$kehuStaff['tel']], L('client.contactsDelete.log'));
                $this->logText(array("type" => "client", "text" => $text));
                $x++;
            }
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('client.contactsDelete.warn'));
            $json['href'] = root . "control/adIndex.html?cla=client&fun=detail&menu=contacts&id=" . $kehu['khid'];
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function logOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('client.log.recordDate') => text(array("name" => "recordDate", 'laydate' => ['type' => 'date', 'range' => '~'])).
                        hidden(array('name' => 'id', 'value' => $this->get('id'))),
                ]
            ]
        ]);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 操作记录
     */
    public function log(): bool|string
    {
        $html = $this->logOptions(false);
        //控件
        $button = "";
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    /**
     * 操作记录
     * @return bool|string
     */
    public function logSearch(): bool|string
    {
        $id = $this->post('id');
        $where = " and orderId = '$id'";
        if ($this->post('recordDate')) {
            $timeArr = explode(' ~ ', $this->post('recordDate'));
            $where .= " and date(time) >='{$timeArr[0]}' and  date(time) <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page = $this->page([
            "table" => "clue_log",
            "where" => " {$where} ",
            "order" => $orderBy['orderBy']
        ]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        $json['html'] = $page['hint'] . "<form name='topicForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function visitOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('client.visit.visitor') => selectMultiple(array('table' => 'staff', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'visitor', 'class' => 'width200')),
                    L('client.visit.achievement')   => text(array("name" => "achievement")) .
                        hidden(array('name' => 'id', 'value' => $this->get('id')))
                ]
            ]
        ]);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 拜访记录
     * @return bool|string
     */
    public function visit()
    {
        $html = $this->visitOptions(false);
        //控件
        $button = "";
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function visitSearch(): bool|string
    {
        $id = $this->post('id');

        //like查询数组
        $like = array(
            "member" => $this->post('visitor'),//电话
            "achievement" => $this->post('achievement'),//备注
        );
        //全等查询数组
        $equal = [];
        $where = search(array("like" => $like, "=" => $equal)) . " and khid = '$id' and factStartTime is not null";
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page = $this->page([
            "table" => "visit_plan",
            "where" => " {$where} ",
            "order" => $orderBy['orderBy']
        ]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "member":
                        $row[] = clueClass::showMember($array['member'], 2);
                        break;
                    case "factStartTime":
                        $row[] = strtotime($array['factStartTime']) > 0 ? ($array['factStartTime'] . '至' . $array['factEndTime']) : '';
                        break;
                    case "hour":
                        $row[] = strtotime($array['factStartTime']) > 0 ? self::hour($array['factStartTime'], $array['factEndTime']) : 0;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        $json['html'] = $page['hint'] . "<form name='visitForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 返回两个时间相差的小时数
     * @param $startTime
     * @param $endTime
     * @return float
     */
    public static function hour($startTime, $endTime): float
    {
        $date1 = strtotime($startTime);
        $date2 = strtotime($endTime);
        if ($date1 > $date2) {
            $temp = $date2;
            $date2 = $date1;
            $date1 = $temp;
        }
        return round(($date2 - $date1) / 3600, 1);
    }

    /**
     * 日志写入
     */
    public function logWrite($id, $type, $text = '')
    {
        $info = query(self::table, " khid = '$id'");
        insert(array(
            'table' => 'clue_log',
            'field' => [
                'id' => self::getId(),
                'coid'=>self::$coid,
                'orderId' => $id,
                'classify' => '客户',
                'type' => $type,
                'text' => $text ?: str_replace(['{{staffName}}','{{type}}','{{companyName}}'], [$this->control['name'],$type,$info['companyName']], L('client.logWrite.text')),
                'staffName' => $this->control['name'],
                'stid' => $this->control['stid'],
                'time' => $this->time
            ]
        ));
    }


    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = L('client.downloadModel.power');
        }  else {
            $exampleData[] = ['K0001','重庆雨木科技','民营企业','邱女士','行政','13000000000','44340001','wechat001','10001','1995-01-01','www.yumukeji.com','001@yumukeji.com',
                '重庆市南岸区国际社区','A类','互联网','软件信息行业','100人以下','官网','初次联系','2021-01-01 00:00:00','默认客户池','张三','YM202111220001','李四,王五','YM202111220002,YM202111220003',
                '重庆雨木科技有限责任公司','中国工商银行','000000000001','重庆市 44310001','0002121111111','重庆市南岸区国际社区','(样例数据，导入时请删除本条数据)'];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '客户编号'=>$example[0],
                            '客户名称'=>$example[1],
                            '性质'=>$example[2],
                            '常用联系人姓名'=>$example[3],
                            '常用联系人职务'=>$example[4],
                            '常用联系人手机'=>$example[5],
                            '常用联系人电话'=>$example[6],
                            '常用联系人微信'=>$example[7],
                            '常用联系人QQ'=>$example[8],
                            '生日'=>$example[9],
                            '网址'=>$example[10],
                            '邮箱'=>$example[11],
                            '地址'=>$example[12],
                            '客户级别'=>$example[13],
                            '客户类别'=>$example[14],
                            '所属行业'=>$example[15],
                            '人员规模'=>$example[16],
                            '来源'=>$example[17],
                            '跟进状态'=>$example[18],
                            '下次跟进时间'=>$example[19],
                            '所属客户池'=>$example[20],
                            '负责人'=>$example[21],
                            '负责人编号'=>$example[22],
                            '协作人'=>$example[23],
                            '协作人编号'=>$example[24],
                            '开票公司名称'=>$example[25],
                            '开户行'=>$example[26],
                            '银行账号'=>$example[27],
                            '注册地址、电话'=>$example[28],
                            '纳税人识别号'=>$example[29],
                            '邮寄地址'=>$example[30],
                            '备注'=>$example[31],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }

            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('client.downloadModel.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /*数据导入*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = L('client.importData.power');
        }  else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $manager = query("staff", "orderNo = '$cell[负责人编号]'");
                    $partner = explode(',', $cell['协作人编号']);

                    $collaborator = [];
                    foreach ($partner as $stid) {
                        $staff = query('staff', "orderNo = '$stid' and orderNo !=''");
                        $collaborator[] = $staff['stid'];
                    }

                    $pool = query('pool', "name = '$cell[所属客户池]' and type = '公客池' and coid='".self::$coid."'");

                    $id = self::getId();
                    $field = [
                        'coid'=>self::$coid,
                        'orderNo'=>$cell['客户编号'],
                        'khid' => $id,
                        "companyName" => $cell['客户名称'],//公司名称
                        "nature" => $cell['性质'],
                        "contactName" => $cell['常用联系人姓名'],//联系人姓名
                        "contactIdentity" => $cell['常用联系人职务'],//联系人身份
                        "contactTel" => $cell['常用联系人手机'],//联系人手机号码
                        "landline" => $cell['常用联系人电话'],//公司座机
                        "contactQQ" => $cell['常用联系人QQ'],//联系人QQ号码
                        "contactWx" => $cell['常用联系人微信'],//联系人微信号
                        "address" => $cell['地址'],
                        "birthDay" => $cell['生日'],
                        "website" => $cell['网址'],
                        "email" => $cell['邮箱'],
                        "level" => $cell['客户级别'],
                        "classify" => $cell['客户类别'],
                        "scale" => $cell['人员规模'],
                        'followTime' => $cell['下次跟进时间'],
                        "industry" => $cell['所属行业'],//所在行业
                        "invoiceCompany" => $cell['开票公司名称'],
                        "postAddress" => $cell['邮寄地址'],
                        "workFlow" => $cell['跟进状态'],
                        "source" => $cell['来源'],
                        "text" => $cell['备注'],
                        "companyNum" => $cell['纳税人识别号'],//纳税人识别号
                        "companyBank" => $cell['开户行'],
                        "companyBankNum" => $cell['银行账号'],//对公账号
                        "companyAddress" => $cell['注册地址、电话'],//开票地址
                        'poolId' => $pool['id']?:self::defaulPoolId(),
                        'manager' => $cell['负责人编号']?$manager['stid']:self::$stid,
                        'collaborator' => implode(',', array_filter(array_unique($collaborator))),
                        'region'=>'',
                        'lat'=>'',
                        'lng'=>'',
                        'stid'=>self::$stid,
                        "updateTime" => date("Y-m-d H:i:s"),//更新时间
                        'time' => $this->time,
                    ];
                    $annotation = [
                        'companyName' => L('client.importData.companyName'),
                        'nature' => L('client.importData.nature'),
                        "contactTel" => L('client.importData.contactTel'),
                        'manager' => L('client.importData.manager'),
                    ];
                    $rules = [
                        'companyName' => 'required',
                        'nature' => 'required',
                        'manager' => 'required',
                    ];
                    $repeat = array(
                        "khid" => $id,
                        "field" => $field,
                        "name" => array("contactQQ" => L('client.importData.contact_qq'), "companyName" => L('client.importData.company_name'), "companyNum" => L('client.importData.tax_number')),
                    );
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if (!empty($cell['负责人编号']) && !$manager['stid']) {
                        $text .= str_replace(['{{i}}'], [$row_list], L('client.importData.staffEmtpy'));
                    } elseif ($result === false) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('client.importData.row')) . $vt->getErrs()[0];
                    }elseif(!empty($field['orderNo']) && static::total(['table'=>'kehu','where'=>"orderNo = '$field[orderNo]' and khid !='$field[khid]'"]) >0){
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('client.importData.repeatError'));
                    }  elseif (!empty($field['email']) && preg_match(checkEmail, $field['email']) == 0) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('client.importData.emailError'));
                    } elseif (!empty($field['contactQQ']) && preg_match(checkInteger, $field['contactQQ']) == 0) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('client.importData.qqError'));
                    } elseif (!empty($field['website']) && preg_match(checkUrl, $field['website']) == 0) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('client.importData.websiteError'));
                    } elseif (!empty($cell['所属客户池']) && empty($pool['id'])) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('client.importData.pollEmpty'));
                    } elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('client.importData.collaborator'));
                    } elseif ($warn = $this->repeat($repeat)) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('client.importData.row')) . $warn;
                    } else {
                        //查看范围
                        $field['see'] = implode(',',array_filter(array_unique(array_merge(explode(',', $field['collaborator']), [$field['manager']]))));
                        //获取经纬度和经纬度逆解析请求时间长，在这里使用不合理
                        /*if (!empty($field['address'])){
                            //解析地址信息 得到经纬度和省市区
                            $locationRes= componentClass::addrToCoordinate($field['address']);
                            if ($locationRes['err_code'] == 0) {
                                $field['lat'] = $locationRes['data']['location']['lat'];
                                $field['lng'] = $locationRes['data']['location']['lng'];
                                $region = componentClass::coordinateToAddr($field['lat'], $field['lng']);
                                if ($region['err_code'] == 0) {
                                    $field['region'] = $region['data']['address_component']['province'] . '-' . $region['data']['address_component']['city'] . '-' . $region['data']['address_component']['district'];
                                }
                            }
                        }*/
                        $userNo = codeTemplateClass::generateCode(self::page,[
                            'prefix' => 'C',
                            'table' => self::table,
                            'field' => 'orderNo',
                            'where' => '',
                        ],$field);
                        $field['orderNo']=$field['orderNo']?:$userNo;
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$row_list}】行：导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行：导入失败：编辑失败<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = str_replace(['{{staffName}}','{{fileName}}'], [$this->control['name'],$_FILES['file']['name']], L('client.importData.log')) . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('client.exportData.power');
        }   else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "khid in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $pool = query('pool', " id = '$array[poolId]'");
                $tags = '';
                $kehu_label = find(array('table' => 'kehu_label', 'where'=>"targetId = '$array[khid]' order by list asc"));
                foreach ($kehu_label['array'] as $val) {
                    $tag_detail = query('tag_detail', "id = '$val[tag_detail_id]'");
                    $tags .= $tag_detail['name'].',';
                }
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '客户名称'=>$array['companyName'],
                            '性质'=>$array['nature'],
                            '常用联系人姓名'=>$array['contactName'],
                            '常用联系人职务'=>$array['contactIdentity'],
                            '常用联系人手机'=>$array['contactTel'],
                            '常用联系人电话'=>$array['landline'],
                            '常用联系人微信'=>$array['contactWx'],
                            '常用联系人QQ'=>$array['contactQQ'],
                            '生日'=>$array['birthDay'],
                            '网址'=>$array['website'],
                            '邮箱'=>$array['email'],
                            '地址'=>$array['address'],
                            '客户级别'=>$array['level'],
                            '客户类别'=>$array['classify'],
                            '所属行业'=>$array['scale'],
                            '人员规模'=>$array['source'],
                            '来源'=>$array['workFlow'],
                            '跟进状态'=>$array['followTime'],
                            '下次跟进时间'=> '',
                            '标签'=>$tags,
                            '所属客户池'=> $pool['name'],
                            '负责人'=> self::findStaff($array['manager']),
                            '协作人'=> clueClass::showMember($array['collaborator'], 2),
                            '开票公司'=>$array['invoiceCompany'],
                            '开户行'=>$array['companyBank'],
                            '银行账号'=>$array['companyBankNum'],
                            '注册地址、电话'=>$array['companyAddress'],
                            '纳税人识别号'=>$array['companyNum'],
                            '邮寄地址'=>$array['postAddress'],
                            '备注'=>$array['text'],
                            '创建人'=> self::findStaff($array['stid']),
                            '更新时间'=>$array['updateTime'],
                            '创建时间'=>$array['time'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('client.exportData.text'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('client.exportData.fileName').".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /**
     * 客户选择器
     * @param $data
     * @return string
     */
    public static function kehuSelect($data){
        $data['name'] = $data['name']??'khid';
        $data['cla'] = $data['cla']??'client';
        $data['fun'] = $data['fun']??'getClientList';
        if (isset($data['value']) && !empty($data['value'])){
            $kehu = query('kehu',"khid = '$data[value]'");
            $data['title'] = $data['title']??($kehu['companyName']?:$kehu['contactName']);
        }
        return componentClass::selectText($data);
    }
    public function getClientList(){
        $val = $this->post('keyword');//关键词
        $json['data'] = [];
        $where = "coid='".self::$coid."'";
        if ($val){
            $where.=" and (companyName like '%$val%' or orderNo like '%$val%')";
        }
        $all = find(array('table' => 'kehu', 'where' => $where." order by orderNo limit 50"));
        foreach ($all['array'] as $array) {
            $json['data'][] = array('title' => $array['companyName']?:$array['contactName'],'orderNo' => $array['orderNo'], 'id' => $array['khid']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'客户编号',
                    'aliasName'=>'客户编号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'性质',
                    'aliasName'=>'性质',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'常用联系人姓名',
                    'aliasName'=>'常用联系人姓名',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'常用联系人职务',
                    'aliasName'=>'常用联系人职务',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'常用联系人手机',
                    'aliasName'=>'常用联系人手机',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'常用联系人电话',
                    'aliasName'=>'常用联系人电话',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'常用联系人微信',
                    'aliasName'=>'常用联系人微信',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'常用联系人QQ',
                    'aliasName'=>'常用联系人QQ',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'生日',
                    'aliasName'=>'生日',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'网址',
                    'aliasName'=>'网址',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'邮箱',
                    'aliasName'=>'邮箱',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'地址',
                    'aliasName'=>'地址',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'客户级别',
                    'aliasName'=>'客户级别',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'客户类别',
                    'aliasName'=>'客户类别',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'所属行业',
                    'aliasName'=>'所属行业',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'人员规模',
                    'aliasName'=>'人员规模',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'来源',
                    'aliasName'=>'来源',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'跟进状态',
                    'aliasName'=>'跟进状态',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'下次跟进时间',
                    'aliasName'=>'下次跟进时间',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'所属客户池',
                    'aliasName'=>'所属客户池',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'负责人',
                    'aliasName'=>'负责人',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'负责人编号',
                    'aliasName'=>'负责人编号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'协作人',
                    'aliasName'=>'协作人',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'协作人编号',
                    'aliasName'=>'协作人编号(多个用英文逗号隔开)',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'开票公司名称',
                    'aliasName'=>'开票公司名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'开户行',
                    'aliasName'=>'开户行',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'银行账号',
                    'aliasName'=>'银行账号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'注册地址、电话',
                    'aliasName'=>'注册地址、电话',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'纳税人识别号',
                    'aliasName'=>'纳税人识别号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'邮寄地址',
                    'aliasName'=>'邮寄地址',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
            ]
        };
    }
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',
                ],
                [
                    'columnName'=>'性质',
                    'aliasName'=>'性质',
                ],
                [
                    'columnName'=>'常用联系人姓名',
                    'aliasName'=>'常用联系人姓名',
                ],
                [
                    'columnName'=>'常用联系人职务',
                    'aliasName'=>'常用联系人职务',
                ],
                [
                    'columnName'=>'常用联系人手机',
                    'aliasName'=>'常用联系人手机',
                ],
                [
                    'columnName'=>'常用联系人电话',
                    'aliasName'=>'常用联系人电话',
                ],
                [
                    'columnName'=>'常用联系人微信',
                    'aliasName'=>'常用联系人微信',
                ],
                [
                    'columnName'=>'常用联系人QQ',
                    'aliasName'=>'常用联系人QQ',
                ],
                [
                    'columnName'=>'生日',
                    'aliasName'=>'生日',
                ],
                [
                    'columnName'=>'网址',
                    'aliasName'=>'网址',
                ],
                [
                    'columnName'=>'邮箱',
                    'aliasName'=>'邮箱',
                ],
                [
                    'columnName'=>'地址',
                    'aliasName'=>'地址',
                ],
                [
                    'columnName'=>'客户级别',
                    'aliasName'=>'客户级别',
                ],
                [
                    'columnName'=>'客户类别',
                    'aliasName'=>'客户类别',
                ],
                [
                    'columnName'=>'所属行业',
                    'aliasName'=>'所属行业',
                ],
                [
                    'columnName'=>'人员规模',
                    'aliasName'=>'人员规模',
                ],
                [
                    'columnName'=>'来源',
                    'aliasName'=>'来源',
                ],
                [
                    'columnName'=>'跟进状态',
                    'aliasName'=>'跟进状态',
                ],
                [
                    'columnName'=>'下次跟进时间',
                    'aliasName'=>'下次跟进时间',
                ],
                [
                    'columnName'=>'标签',
                    'aliasName'=>'标签',
                ],
                [
                    'columnName'=>'所属客户池',
                    'aliasName'=>'所属客户池',
                ],
                [
                    'columnName'=>'负责人',
                    'aliasName'=>'负责人',
                ],
                [
                    'columnName'=>'协作人',
                    'aliasName'=>'协作人',
                ],
                [
                    'columnName'=>'开票公司',
                    'aliasName'=>'开票公司',
                ],
                [
                    'columnName'=>'开户行',
                    'aliasName'=>'开户行',
                ],
                [
                    'columnName'=>'银行账号',
                    'aliasName'=>'银行账号',
                ],
                [
                    'columnName'=>'注册地址、电话',
                    'aliasName'=>'注册地址、电话',
                ],
                [
                    'columnName'=>'纳税人识别号',
                    'aliasName'=>'纳税人识别号',
                ],
                [
                    'columnName'=>'邮寄地址',
                    'aliasName'=>'邮寄地址',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
                [
                    'columnName'=>'创建人',
                    'aliasName'=>'创建人',
                ],
                [
                    'columnName'=>'更新时间',
                    'aliasName'=>'更新时间',
                ],
                [
                    'columnName'=>'创建时间',
                    'aliasName'=>'创建时间',
                ],
            ]
        };
    }
}
